#!/bin/bash

dockerVersion="19.03.15"
ARCH="x86_64"
#ARCH="aarch64"

set -e

# 下载解压二进制安装包
if [[ -f docker-${dockerVersion}.tgz ]]; then
    echo "docker-${dockerVersion}.tgz安装包已存在，无需下载，正在解压安装包"
    tar xf docker-${dockerVersion}.tgz
    mv docker/* /usr/bin
    echo "docker-${dockerVersion}.tgz安装包解压完成"
else
    echo "docker-${dockerVersion}.tgz安装包下载中......"
    wget https://download.docker.com/linux/static/stable/${ARCH}/docker-${dockerVersion}.tgz >> /dev/null
    if [[ -f docker-${dockerVersion}.tgz ]]; then
        echo "docker-${dockerVersion}.tgz安装包下载已完成，正在解压安装包"
        tar xf docker-${dockerVersion}.tgz
        mv docker/* /usr/bin
        echo "docker-${dockerVersion}.tgz安装包解压完成"
    else 
        echo "docker-${dockerVersion}.tgz安装包下载失败"
    fi
fi

# 配置systemd启停docker
cat > /usr/lib/systemd/system/docker.service << EOF
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target
Requires=docker.socket 
[Service]
Type=notify
ExecStart=/usr/bin/dockerd
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yes
KillMode=process
OOMScoreAdjust=-500
[Install]
WantedBy=multi-user.target
EOF

cat > /usr/lib/systemd/system/docker.socket << EOF
[Unit]
Description=Docker Socket for the API
[Socket]
ListenStream=/var/run/docker.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker
[Install]
WantedBy=sockets.target
EOF

# 配置docker daemon.json
if [[ -d /etc/docker ]]; then
    echo "/etc/docker目录已存在"
else
    mkdir /etc/docker
fi
cat > /etc/docker/daemon.json << EOF
{
  "exec-opts":["native.cgroupdriver=systemd"], 
  "registry-mirrors":["https://fl7idj1l.mirror.aliyuncs.com"],
  "log-driver":"json-file",
  "log-opts": {
    "max-size":"100m"
  } 
}
EOF

# 添加docker组，二进制不会自动添加
groupadd  docker 
#usermod -a -G docker user1

# 启动docker并设置开机启动
systemctl daemon-reload
systemctl start docker
systemctl enable docker >> /dev/null
systemctl status docker | grep -o running >> /dev/null
if [[ $? -eq 0 ]]; then
    echo "docker启动成功"
else
    echo "docker启动失败"
fi